<?php
// +----------------------------------------------------------------------
// | 有小象汇 自研正版源码 赋能开发者
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 http://www.uxphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 有小象汇并不是自由软件，未经许可不能去掉有小象汇相关版权
// +----------------------------------------------------------------------
// | Author:  有小象汇
// +----------------------------------------------------------------------

namespace app\services\car;


use app\dao\car\CarTypeInfoDao;
use app\model\car\CarBrand;
use app\model\car\CarCategory;
use app\model\car\CarType;
use app\model\car\CarTypeInfo;
use app\services\BaseServices;
use crmeb\exceptions\AdminException;
use crmeb\services\FormBuilder as Form;
use think\facade\Route as Url;

/**
 * Class CarTypeInfoServices
 * @package app\services\shendeng
 */
class CarTypeInfoServices extends BaseServices
{
    public function __construct(CarTypeInfoDao $dao)
    {
        $this->dao = $dao;
    }
    /**
     * 列表
     * @param array $where
     * @param string $field
     * @param bool $is_page
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList(array $where = [],string $field = '*',bool $is_page = false){
        $page = $limit = 0;
        if($is_page){
            [$page, $limit] = $this->getPageValue();
        }
        $list = $this->dao->getList($where,$field,$page,$limit);
        foreach ($list as &$item){
            $item['gear'] = $item['gear'] = 'auto' ? '自动挡' : '手动挡';
        }
        $count = $this->dao->count($where);
        return compact('list','count');
    }
    /**
     * 添加/修改
     * @param int $id
     * @return array
     * @throws \FormBuilder\Exception\FormBuilderException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add(int $id){
        $info = $this->dao->get($id);
        $brand = CarBrand::field('id as value,brand_name as label')->where(['is_del'=>0,'status'=>1])->select()->toArray();
        $category = CarCategory::field('id as value,cate_name as label')->where(['is_del'=>0,'status'=>1])->select()->toArray();
        $field = array();
        $title = $id ? '修改' : '添加';
        $field[] = Form::hidden('id', $id);
        $field[] = Form::input('type_name', '车型名称', $info['type_name']??'')->required();
        $field[] = Form::select('brand_id', '车辆品牌', $info['brand_id']??'')->setOptions($brand);
        $field[] = Form::select('cate_id', '所属分类', $info['cate_id']??'')->setOptions($category);
        $field[] = Form::input('power', '车辆排量', $info['power']??'')->style(['width'=>'100%'])->required();
        $field[] = Form::number('seat_num', '座位数量', $info['seat_num']??'')->style(['width'=>'100%'])->required();
//        $field[] = Form::number('oil_box', '油箱大小', (int)$info['oil_box']??'')->style(['width'=>'100%'])->required();
        $field[] = Form::input('jiazhao_grade', '驾照等级', $info['jiazhao_grade']??'')->style(['width'=>'100%'])->required();
        $field[] = Form::input('bed', '床位数', $info['bed']??'')->style(['width'=>'100%'])->required();
        $field[] = Form::input('fuel', '燃油类型', $info['fuel']??'')->style(['width'=>'100%'])->required();
        $field[] = Form::text('function', '房车功能', $info['function']??'')->style(['width'=>'100%'])->required();
        $field[] = Form::input('chang', '车长(cm)', $info['chang']??'')->style(['width'=>'100%'])->required();
        $field[] = Form::input('kuan', '车宽(cm)', $info['kuan']??'')->style(['width'=>'100%'])->required();
        $field[] = Form::input('gao', '车高(cm)', $info['gao']??'')->style(['width'=>'100%'])->required();
        $field[] = Form::frameImage('pic','车辆图片',Url::buildUrl('/admin#/admin/widget.images/index',array('fodder'=>'pic')),$info['pic']??'')->icon('ios-add')->width('950px')->height('505px')->modal(['footer-hide' => true]);
        $field[] = Form::radio('gear','车辆档位',$info['gear']??'auto')->options([['label'=>'自动挡','value'=>'auto'],['label'=>'手动挡','value'=>'hand']])->col(['span'=>12]);
        $field[] = Form::radio('status','是否显示',$info['status']??1)->options([['label'=>'显示','value'=>1],['label'=>'隐藏','value'=>0]])->col(['span'=>12]);
        $field[] = Form::radio('is_hot','是否热销',$info['is_hot']??1)->options([['label'=>'是','value'=>1],['label'=>'否','value'=>0]])->col(['span'=>12]);
        $field[] = Form::radio('is_recommend','是否推荐',$info['is_recommend']??1)->options([['label'=>'是','value'=>1],['label'=>'否','value'=>0]])->col(['span'=>12]);

        return create_form($title, $field, Url::buildUrl('/car/type/info/save'), 'POST');
    }
    /**
     * 添加/修改保存
     * @param int $id
     * @param array $data
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function save(int $id, array $data){
        $type = $this->dao->getOne(['id' => $id,'is_del'=>0]);
        if ($id) {
            if (!$this->dao->get($id)) throw new AdminException('数据不存在');
            if ($this->dao->update($id, $data)) {
                return true;
            } else {
                throw new AdminException('修改失败或者您没有修改什么');
            }
        } else {
            unset($data['id']);
            $data['add_time'] = time();
            if ($this->dao->save($data)) {
                return true;
            } else {
                throw new AdminException('添加失败');
            }
        }
    }
    /**
     * 删除
     * @param int $id
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delType(int $id){
        $type = $this->dao->get($id);
        $this->check($type,"type");
        if ($type) {
            $data['is_del'] = 1;
            $data['delete_time'] = time();
            if (!$this->dao->update($id,$data)) {
                throw new AdminException('删除失败,请稍候再试!');
            }
        }
        return '删除成功!';
    }

    /**
     * 显示/隐藏
     * @param int $id
     * @param int $status
     * @param $type
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function setShow(int $id, int $status,$type){
        $typeInfo = $this->dao->getOne(['id' => $id,'is_del'=>0]);
        if (!$typeInfo){
            throw new AdminException('数据不存在');
        }
        if($type == 'status'){
            if ($this->dao->update($id, ['status' => $status])) {
                return $status == 1 ? '显示成功' : '隐藏成功';
            } else {
                throw new AdminException($status == 1 ? '显示失败' : '隐藏失败');
            }
        }elseif($type == 'is_hot'){
            if ($this->dao->update($id, ['is_hot' => $status])) {
                return $status == 1 ? '热销成功' : '不热销成功';
            } else {
                throw new AdminException($status == 1 ? '热销失败' : '不热销失败');
            }
        }elseif($type == 'is_recommend'){
            if ($this->dao->update($id, ['is_recommend' => $status])) {
                return $status == 1 ? '推荐成功' : '不推荐成功';
            } else {
                throw new AdminException($status == 1 ? '推荐失败' : '不推荐失败');
            }
        }
    }

    /**
     * 车型下拉列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTypeInfoSelect(){
        $list = CarTypeInfo::where(['is_del'=>0])->select()->toArray();
        $typeInfo = [];
        foreach ($list as $item){
            $typeInfo[] = ['value'=>$item['id'],'label'=>$item['type_name']];
        }
        return $typeInfo;
    }

    /**
     * 获取条件与指定字段车型
     * @param array $where
     * @param string $field
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTypeInfo(array $where = [],string $field = '*'){
        $list = CarTypeInfo::field($field)->where($where)->select()->toArray();
        return $list;
    }

    /**
     * 获取推荐车型
     * @return array
     */
    public function getIsRecommendCar(){
        $carRecommend = CarType::alias('t')
            ->field('t.id,t.place_id,i.type_name,min(t.price) as price,i.pic,i.power,i.gear,i.seat_num')
            ->join('car_type_info i','i.id=t.type_info_id','left')
            ->where(['i.is_recommend'=>1,'i.is_del'=>0,'t.is_del'=>0])
            ->group('i.id')
            ->select()->toArray();
        foreach($carRecommend as $k=>$v){
            if($v['gear']=="auto"){
                $carRecommend[$k]['gear'] = "自动挡";
            }else{
                $carRecommend[$k]['gear'] = "手动挡";
            }
        }
        $price = min(array_column($carRecommend,'price'));
        return compact('carRecommend','price');
    }
}
